/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package businesscard.servlet;

import bc.entity.Quanhuyen;
import bc.entity.Quyen;
import businesscard.DAO.UserDAO;
import bc.entity.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Welcome
 */
@WebServlet(name = "UserController", urlPatterns = {"/UserController"})
public class UserController extends HttpServlet {
private HttpSession session;
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            String urlDispatcher = "";
            if (action.equals("Login")) {
                UserDAO userDAO = new UserDAO();
                String username = request.getParameter("txtUsername");
                String pass=request.getParameter("txtPassword");
                String password = userDAO.md5(pass);
                try {
                    if (!username.isEmpty() && !password.isEmpty()) {                
                        User result = userDAO.authenticate(username, password);
                        urlDispatcher = "invalid.jsp";
                        if (result != null) {
                            Quyen role= result.getQuyen();
                            session = request.getSession(true);
                            User user=new User();
                            user.setUser(username);
                            user.setPassword(password);
                            user.setQuyen(role);
                            session.setAttribute("USER", user);
                            urlDispatcher = "index.jsp";                         
                        }
                        else
                             urlDispatcher = "invalid.jsp";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
               
            } else if (action.equals("Logout")) {
                 session = request.getSession(true);
                session.invalidate();
                response.sendRedirect("index.jsp");
            }  else if (action.equals("Update")) {
                Integer quan=Integer.parseInt(request.getParameter("txtQuanhuyen"));
                Quanhuyen quanhuyen=new Quanhuyen();
                quanhuyen.setIdQuanhuyen(quan);
                String sodt = request.getParameter("txtDienthoai");
                User user=(User)request.getSession().getAttribute("USER");
                String username=user.getUser();
                String password=user.getPassword();
                Quyen idQuyen=user.getQuyen();
                String date = request.getParameter("Ngay");
                String month = request.getParameter("Thang");
                String year = request.getParameter("Nam");
                String ngaysinh = year + "-" + month + "-" + date;
                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date dt = ft.parse(ngaysinh);
                
                int gioitinh = Integer.parseInt(request.getParameter("txtGioitinh"));
                String email = request.getParameter("txtEmail");
                String cmnd = request.getParameter("txtSoCMND");
                String diachi=request.getParameter("txtDiachi");
                UserDAO userDAO=new UserDAO();    
                User user1=userDAO.getUser2(username);
                int point=user1.getPoint();
                String hinhanh=user1.getHinhanh();
                Integer id_user=user1.getIdUser();
                User account = new User(idQuyen, quanhuyen,username,password,diachi, sodt, email, gioitinh, dt, cmnd,point,hinhanh);
                UserDAO accountDAO = new UserDAO();
                accountDAO.update(account, id_user);
                urlDispatcher = "trangcanhan.jsp";
            } else if (action.equals("Delete")) {
                String txtSearch = request.getParameter("txtSearch");
                String id = request.getParameter("txtId");
                UserDAO accountDAO = new UserDAO();
                accountDAO.delete(Integer.parseInt(id));
                urlDispatcher = "Controller?action=Search&txtSearch=" + txtSearch;
            } else if (action.equals("Add")) {
               String txtSearch = request.getParameter("txtSearch");
                String username = request.getParameter("txtUsername");
                String password = request.getParameter("txtPassword");
               // String lastname = request.getParameter("txtLastname");
                String id = request.getParameter("txtId");
                int thanhpho = Integer.parseInt(request.getParameter("txtThanhpho"));
                //String roles = request.getParameter("cbRole");
                String sodt = request.getParameter("txtSodt");

                String ngaysinh = request.getParameter("txtNgaysinh");
                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date dt = ft.parse(ngaysinh);

                int gioitinh = Integer.parseInt(request.getParameter("txtGioitinh"));
                String email = request.getParameter("txtEmail");
                String cmnd = request.getParameter("txtSocmnd");
                int idQuyen=Integer.parseInt(request.getParameter("txtSocmnd"));
                int point=0;
                String hinhanh=request.getParameter("fileUp");
              //  User account = new User(username, password, idQuyen, thanhpho, sodt, email, gioitinh, dt, cmnd,point,hinhanh);
                UserDAO accountDAO = new UserDAO();
               // accountDAO.Save(account);
                urlDispatcher = "Controller?action=Search&txtSearch=" + txtSearch;
            }else if(action.equals("Edit Avatar")){
                User user=(User)request.getSession().getAttribute("USER");
                String username=user.getUser();
                String hinh=request.getParameter("txtAvatar");
                UserDAO user2=new UserDAO();
                user2.updateHinh(username, hinh);
                urlDispatcher = "trangcanhan.jsp";
            }
            RequestDispatcher rd = request.getRequestDispatcher(urlDispatcher);
            rd.forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
